package com.zhugang.week13.stack;

/**
 * @program algorithms
 * @description: trap
 * @author: chanzhugang
 * @create: 2022/11/12 23:21
 */
public class Trap {

    /**
     * 42 接雨水
     * https://leetcode.cn/problems/trapping-rain-water/
     *
     * @param height
     * @return O(n ^ 2)
     */
    public int trap(int[] height) {
        /**
         * 核心：每个柱子盛水量 = min(lh, rh) - curh, 总的盛水量等于每个柱子盛水量之和
         */
        int n = height.length;
        int result = 0;
        for (int i = 1; i < n - 1; i++) {
            int lh = 0;
            for (int j = 0; j < i; j++) {
                lh = Math.max(lh, height[j]);
            }

            int rh = 0;
            for (int j = i + 1; j < n; j++) {
                rh = Math.max(rh, height[j]);
            }
            // 核心：每个柱子的盛水量
            int carry = Math.min(lh, rh) - height[i];
            if (carry < 0) carry = 0;
            result += carry;
        }
        return result;
    }


    public int trap2(int[] height) {
        /**
         * 前缀后缀统计最大值，具体见第十一周专项训练
         * O(n)
         */
        int n = height.length;
        int[] leftMax = new int[n];
        int max = 0;
        for (int i = 0; i < n; i++) {
            // 包含自己
            leftMax[i] = Math.max(max, height[i]);
            max = leftMax[i];
        }

        int[] rightMax = new int[n];
        max = 0;
        for (int i = n - 1; i >= 0; i--) {
            // 包含自己
            rightMax[i] = Math.max(max, height[i]);
            max = rightMax[i];
        }

        int result = 0;
        for (int i = 1; i < n - 1; i++) {
            // 因为包含了自己，所以不用特殊处理0的情况
            result += Math.min(leftMax[i], rightMax[i]) - height[i];
        }
        return result;
    }
}